from moviepy.editor import *
import re
import json
import random
import uuid
with open('videos_ssyer.json','r',encoding='utf8') as vj:
    # videosJson = json.load(videosJson)
    videoJson = json.load(vj)


# 获取随机素材
def randomVideos():
    # print("randomVideos")
    return videoJson[
        random.randint(0, len(videoJson) - 1)
    ]["url"]


# 获取音频(音轨)相关信息dict
def getAudio(url):
    # print("getAudio")
    audio_clip = VideoFileClip(url)
    return {
        'duration': audio_clip.duration,
        'clip': audio_clip.audio
    }


# 根据时长获取素材信息list
def getVideoByDuration(duration):
    # 视频信息数组
    clip_data_list = []
    clip_list = []
    # 初始化开始时间
    video_start = 0
    while(video_start < duration):
        # 持续时间(int)
        clip_duration = random.randint(5, 10)
        # if clip_duration > duration - video_start:
        #     clip_duration = duration - video_start
        # 结束时间
        video_end = video_start + clip_duration
        # 视频片段url(str)
        clip_url = randomVideos()
        # 片段文件
        clip = VideoFileClip(clip_url)
        # 片段开始时间 (int)
        clip_start = random.randint(0, int(clip.duration) - clip_duration)
        # 片段结束时间(int)
        clip_end = clip_start + clip_duration
        # video_start = video_end
        # return clip_url, clip_start, clip_end, video_start, clip_duration, 
        clip_list.append(clip.subclip(clip_start,clip_end).set_start(video_start).set_pos(("center","center")))
        clip_data_list.append({
            'video_start': video_start, 
            'video_end': video_end,
            'clip_duration': clip_duration, 
            'clip': clip.subclip(clip_start,clip_end),
            'clip_url': clip_url, 
            'clip_start': clip_start, 
            'clip_end': clip_end
        })
        # 视频信息汇总
        # clip = clip_data['clip']
        # clip_data_list.append(clip.set_start(clip_data['video_start']).set_pos(("center","center")))
        # 开始时间递增
        video_start = video_end
    # 保存素材列表
    print(clip_data_list)
    # saveData(clip_data_list)
    # return clip_data_list, clip_list
    return CompositeVideoClip(clip_list, size=(1920, 1080))



# # 视频拼接
# def splicingVideos(clip_list):
#     # clip_list = clipFormart(clip_data_list)
#     # print("splicingVideos")
#     return CompositeVideoClip(clip_list, size=(480, 360))


# 保存视频信息
# def saveData(data):
#     # print("saveData")
#     with open('video_data.json','r',encoding='utf8') as vdj:
#     # videosJson = json.load(videosJson)
#         video_data = json.load(vdj)
#         video_data[uuid.uuid1()] = data
#         json.dumps(video_data)
#         # print('视频信息已保存')


# 分段拼接
def splicingEvery(audio_video):
    duration = audio_video.duration
    if duration > 300:
        audio_video1 = audio_video.subclip(0, duration / 2)
        splicingEvery(audio_video1)
        audio_video2 = audio_video.subclip(duration / 2, duration)
        splicingEvery(audio_video2)
    else:
        clip = getVideoByDuration(duration)
        writeVideo(clip.set_audio(audio_video.audio))


# def splicingVideoByDuration(duration):
    


# 根据音频地址提取音频
def getVideoByAudio(audio_url):
    splicingEvery(VideoFileClip(audio_url))


# 根据音频文件输出视频



# 添加音轨且输出视频
def addAudio(audio, clip):
    # print("addAudio")
    # 加音轨
    writeVideo(clip.set_audio(audio))


# 
def writeVideo(clip, video_name = f"{uuid.uuid1()}.mp4"):
    # print("writeVideo")
    # 保存视频信息
    # video_name = "final_clip.mp4"
    # saveData({'name': video_name, 'value': clip_data_list})
    # 输出视频
    clip.write_videofile(video_name)
    

def main():
    # print("main")
    # 片头
    # top_url = 'srt/top.mp4'
    # top_video = VideoFileClip(top_url)
    # 音频转视频
    writeVideo(getVideoByDuration(20))
    # getVideoByAudio('E:/pybase/gitbase/audio.mp4')
    


def test(duration):
    clip = getVideoByDuration(duration)
    writeVideo(clip)
    # VideoFileClip(randomVideos()).write_videofile("final.mp4")
#
# main()是根据90行的文件为音轨，当前音轨文件是视频文件，如果是纯音频，须将67、68行注释换一下#
# test()方法可以直接输出没有音轨的视频()里需要加入视频时长
# #
if __name__ == '__main__':
    main()
    # test()